package com.coincalf.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.coincalf.dto.UserBankDTOMapper;
import com.coincalf.entity.User;
import com.coincalf.entity.UserBank;
import com.coincalf.enums.BankStatus;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.framework.http.Response;
import com.coincalf.service.UserBankService;
import com.coincalf.service.UserService;
import com.coincalf.user.dto.UserBankDTO;
import com.coincalf.web.vo.UserBankForm;
import com.coincalf.web.vo.mappers.UserBankMapper;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 * <p>
 * 用户绑卡信息表 前端控制器
 * </p>
 *
 * @author qiang
 * @since 2018-03-06
 */
@RestController
@RequestMapping("/v3/cards")
@Api(value = "用户绑卡信息", description = "用户绑卡信息表")
public class UserBankController {

    @Autowired
    private UserBankService userBankService;
    @Autowired
    private CommonController commonController;


    /**
     * 绑卡列表
     *
     * @param page
     * @return
     */
    //@PreAuthorize("isAuthenticated()")
    @GetMapping
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "请求成功", response = Page.class),
    })
    @ApiOperation(value = "绑卡列表", httpMethod = "GET")
    //@ApiOperation(value = "绑卡列表", httpMethod = "GET", authorizations = {@Authorization(value = "Authorization")})
    public Object list(HttpServletRequest request, Page<UserBank> page) {
        Long userId = commonController.getUserId(request);
        EntityWrapper<UserBank> ew = new EntityWrapper<>();
        if (null == userId) {
            return "用户未登录";
        }
        ew.eq("user_id", userId);
        ew.orderBy("created", false);
        return userBankService.selectPage(page, ew);
    }

    //@PreAuthorize("isAuthenticated()")
    //@ApiOperation(value = "OUTSIDE-002 C2C个人银行卡", notes = "银行卡", httpMethod = "GET", authorizations = {@Authorization(value = "Authorization")})
    //@GetMapping(value = "/bank")
    //@ApiOperation(value = "OUTSIDE-002 C2C个人银行卡", notes = "银行卡", httpMethod = "GET")
    //public Object bank(HttpServletRequest request) {
    //    Long userId = commonController.getUserId(request);
    //    EntityWrapper<UserBank> e = new EntityWrapper<>();
    //    e.eq("user_id", userId);
    //    e.eq("status", 1);
    //    return Response.ok(userBankService.selectOne(e));
    //}

    /**
     * 添加银行卡
     *
     * @param form
     * @return
     */
    @PostMapping("/bind")
    @ApiOperation(value = "添加银行卡", httpMethod = "POST")
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "请求成功", response = Response.class),
            @ApiResponse(code = 40003, message = "短信验证码错误", response = Response.class)
    })
    //@PreAuthorize("isAuthenticated()")
    //@ApiOperation(value = "添加银行卡", httpMethod = "POST", authorizations = {@Authorization(value = "Authorization")})
    public Object bind(
            HttpServletRequest request,
            @ApiParam(value = "银行卡信息", required = true) @RequestBody @Valid UserBankForm form
    ) {
        User user = commonController.getUser(request);
        if (!new BCryptPasswordEncoder().matches(form.getPayPassword(), user.getPaypassword())) {
            throw new GlobalDefaultException(2012);
        }
        EntityWrapper<UserBank> wrapper = new EntityWrapper<>();
        wrapper.eq("bank_card", form.getBankCard()).eq("user_id", user.getId());
        UserBank userBank = userBankService.selectOne(wrapper);
        if (userBank != null) {
            throw new GlobalDefaultException(50060);
        }
        userBank = UserBankMapper.INSTANCE.map(form);
        userBank.setUserId(user.getId());
        userBank.setLastUpdateTime(new Date());
        userBank.setCreated(new Date());
        userBank.setStatus(BankStatus.USE.getValue());
        boolean flag;
        if (form.getId() != 0L) {
            flag = userBankService.updateById(userBank);
            if (!flag) {
                throw new GlobalDefaultException(20009);
            }
        } else {
            flag = userBankService.insert(userBank);
            if (!flag) {
                throw new GlobalDefaultException(20008);
            }
        }
        return Response.ok();
    }

    /**
     * 查询用户银行卡
     *
     * @return
     */
    //@GetMapping("/queryCard")
    //public UserBankDTO selectByUserId(HttpServletRequest request) {
    //    Long userId = commonController.getUserId(request);
    //    EntityWrapper<UserBank> ew = new EntityWrapper<>();
    //    ew.eq("user_id", userId);
    //    UserBank userBank = userBankService.selectOne(ew);
    //    return UserBankDTOMapper.INSTANCE.from(userBank);
    //}

}
